<?php

namespace app\admin\controller\box;

use fast\QRcode;
use app\common\controller\Backend;
use ZipArchive;

/**
 * 库存监控
 *
 * @icon fa fa-circle-o
 */
class Stock extends Backend {

    /**
     * Box模型对象
     * @var \app\admin\model\Box
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\Box;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit, $having) = $this->buildparams(null, null, [], ['box_id' => 'fa_box.box_id', 'status' => 'fa_box.status', 'box_no' => 'fa_box.box_no', 'user_id' => 'fa_user_box.user_id', 'createtime' => 'fa_box.createtime', 'stock' => 'fa_box.box_id', 'worth' => 'fa_box.box_id'], ['stock' => 'sum(fa_user_box_goods.stock_num)']);

            $admin_info = db('admin')->where('id', $this->auth->id)->find();
            $admin_where = [];

            if ($admin_info['identity'] == 1) {
                if ($admin_info['province'] != 0) {
                    $admin_where['fa_user_box.province'] = $admin_info['province'];
                }
                if ($admin_info['city'] != 0) {
                    $admin_where['fa_user_box.city'] = $admin_info['city'];
                }
                if ($admin_info['area'] != 0) {
                    $admin_where['fa_user_box.area'] = $admin_info['area'];
                }
                if ($admin_info['quarters_id'] != 0) {
                    $admin_where['fa_user_box.quarters_id'] = $admin_info['quarters_id'];
                }
                if ($admin_info['unit_id'] != 0) {
                    $admin_where['fa_user_box.unit_id'] = $admin_info['unit_id'];
                }
                if ($admin_info['room_id'] != 0) {
                    $admin_where['fa_user_box.room_id'] = $admin_info['room_id'];
                }
            } else if ($admin_info['identity'] == 2) {
                $admin_where['fa_user_box.box_no'] = ['in', $admin_info['box_nos']];
            }

            $total = $this->model
                    ->join('fa_user_box', 'fa_box.box_id = fa_user_box.box_id and fa_user_box.status = 1 ', 'left')
                    ->join('fa_user_box_goods', 'fa_user_box.user_box_id = fa_user_box_goods.user_box_id', 'left')
                    ->where($where)
                    ->where($admin_where)
                    ->group('fa_user_box_goods.user_box_id')
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->field('fa_box.*,fa_user_box.user_box_id,fa_user_box.user_id,fa_user_box.province_name,fa_user_box.city_name,fa_user_box.area_name,fa_user_box.quarters_id,fa_user_box.unit_id,fa_user_box.room_id,fa_user_box.contacts,fa_user_box.telephone,fa_user_box.remark,fa_user_box.admin_remark,fa_user_box.place_time_start,sum(fa_user_box_goods.stock_num) as stock,sum(fa_user_box_goods.stock_num*fa_user_box_goods.selling_price) as worth,fa_user_box.sex')
                    ->join('fa_user_box', 'fa_box.box_id = fa_user_box.box_id and fa_user_box.status = 1 ', 'left')
                    ->join('fa_user_box_goods', 'fa_user_box.user_box_id = fa_user_box_goods.user_box_id', 'left')
                    ->where($where)
                    ->where($admin_where)
                    ->group('fa_user_box_goods.user_box_id');

            if ($having) {
                $list->having('sum( fa_user_box_goods.stock_num ) BETWEEN ' . $having[0][2][0] . ' and ' . $having[0][2][1]);
            }
            $sort1 = $this->request->get("sort", "id");
            $order1 = $this->request->get("order", "DESC");

            if ($sort1 == 'stock') {
                $list->orderRaw('sum(fa_user_box_goods.stock_num) ' . $order1);
            } else if ($sort1 == 'worth') {
                $list->orderRaw('sum(fa_user_box_goods.stock_num*fa_user_box_goods.selling_price) ' . $order1);
            } else {
                $list->order($sort, $order);
            }

            $list->limit($offset, $limit);
            $list = $list->select();

            $list = collection($list)->toArray();
            if ($list) {
                foreach ($list as &$val) {
                    if ($val['sex'] == 0) {
                        $val['sex'] = '女';
                    } else {
                        $val['sex'] = '男';
                    }

                    $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
                    $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
                    $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');

                    //计算成本-收益

                    $cost = db('user_box_goods')
                            ->alias('ubg')
                            ->field('sum(g.purchase_price*ubg.total_num)as cost')
                            ->join('fa_goods g', 'g.goods_id = ubg.goods_id', 'left')
                            ->where('ubg.user_box_id', $val['user_box_id'])
                            ->find();

                    $benefit = db('order')
                            ->where('user_box_id', $val['user_box_id'])
                            ->where('is_pay', 1)
                            ->where('type', 1)
                            ->sum('pay_price');

                    $val['cost'] = round($benefit - $cost['cost'], 2);
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function detail() {
        $id = $this->request->param('ids');
        if (empty($id)) {
            $this->error('请选择盒子');
        }

        $box_info = db('user_box')
                ->alias('ub')
                ->field('ub.*,u.nick_name,u.phone')
                ->join('fa_users u', 'ub.user_id=u.user_id', 'left')
                ->where('user_box_id', $id)
                ->find();

        if ($box_info) {
            $box_info['room_name'] = db('house')->where(['house_id' => $box_info['room_id']])->value('house_name');
            $box_info['unit_name'] = db('house')->where(['house_id' => $box_info['unit_id']])->value('house_name');
            $box_info['quarters_name'] = db('house')->where(['house_id' => $box_info['quarters_id']])->value('house_name');
        } else {
            $this->error('没有找到盒子信息');
        }


        //用户申请补货的商品
        $list = db('user_box_goods')
                ->alias('ubg')
                ->field('ubg.*,g.goods_title,g.goods_model,g.goods_spec,g.goods_weight,g.purchase_price,g.selling_price as goods_price,gc.cate_title,gb.brand_title')
                ->join('fa_goods g', 'ubg.goods_id = g.goods_id', 'left')
                ->join('fa_goods_cate gc', 'gc.cate_id = g.cate_id', 'left')
                ->join('fa_goods_brand gb', 'gb.brand_id = g.brand_id', 'left')
                ->where('user_box_id', $id)
                ->select();

        if ($list) {
            foreach ($list as &$val) {
                $val['sale_num'] = db('order')
                        ->alias('o')
                        ->join('fa_order_goods og', 'o.order_id = og.order_id')
                        ->where('user_box_id', $id)
                        ->where('box_goods_id', $val['box_goods_id'])
                        ->where('type', 1)
                        ->where('status', 10)
                        ->sum('buy_num');
            }
            unset($val);
        }

        $this->assign('list', $list);
        $this->assign('info', $box_info);
        $this->assign('ids', $id);
        return $this->view->fetch();
    }

    //完成补货
    public function replen() {
        $id = $this->request->param('ids');


        if ($this->request->isPost()) {
            if (empty($id)) {
                $this->error('请确认要补货的盒子');
            }
            $order_id = $id;

            //取出该订单的所有补货商品

            $replen_goods_list = db('replen_goods')->where('order_id', $order_id)->where('is_replen', 0)->select();

            if (empty($replen_goods_list)) {
                $this->error('没有要补货的商品');
            }
            $order_info = db('order')->where('order_id', $order_id)->find();

            $is_replen = 0;
            //添加库存变动流水

            $stock_log['change_matters'] = 2;
            $stock_log['replen_id'] = $order_id;
            foreach ($replen_goods_list as $val) {
                $stock_log['change_type'] = 0;
                if ($val['buy_num'] > 0) {
                    $is_replen = 1;
                    $stock_log['change_type'] = 1;
                }
                $user_box_goods_info = db('user_box_goods')->where(['goods_id' => $val['goods_id'], 'user_box_id' => $order_info['user_box_id']])->find();

                if ($user_box_goods_info) {
                    db('user_box_goods')->where(['goods_id' => $val['goods_id'], 'user_box_id' => $order_info['user_box_id']])->setInc('stock_num', $val['buy_num']);
                    db('user_box_goods')->where(['goods_id' => $val['goods_id'], 'user_box_id' => $order_info['user_box_id']])->setInc('total_num', $val['buy_num']);
                    $stock_log['box_goods_id'] = $user_box_goods_info['box_goods_id'];
                    $stock_log['quantity'] = $user_box_goods_info['stock_num'] + $val['buy_num'];
                } else {
                    $user_box_goods['goods_id'] = $val['goods_id'];
                    $user_box_goods['user_box_id'] = $order_info['user_box_id'];
//                    $user_box_goods['box_goods_id'] = $val['box_goods_id'];

                    $quarters_id = db('user_box')->where('user_box_id', $order_info['user_box_id'])->value('quarters_id');

                    $user_box_goods['selling_price'] = db('house_goods')->where(['house_id' => $quarters_id, 'goods_id' => $val['goods_id']])->value('selling_price');
                    $user_box_goods['stock_num'] = $val['buy_num'];
                    $user_box_goods['total_num'] = $val['buy_num'];
                    $stock_log['quantity'] = $val['buy_num'];
                    $stock_log['box_goods_id'] = db('user_box_goods')->insertGetId($user_box_goods);
                }

                $stock_log['goods_id'] = $val['goods_id'];
                $stock_log['change_amount'] = $val['buy_num'];

                db('stock_log')->insert($stock_log);
            }

            $orderData['updatetime'] = date('Y-m-d H:i:s');
            $orderData['is_replen'] = $is_replen;
            $orderData['status'] = 10;
            db('order')->where('order_id', $order_id)->update($orderData);
            db('replen_goods')->where('order_id', $order_id)->where('is_replen', 0)->update(['is_replen' => 1]);
            $this->success();
        } else {

            if (empty($id)) {
                $this->error('请确认要补货盒子');
            }

            $box_info = db('user_box')
                    ->alias('ub')
                    ->field('ub.*')
                    ->where('user_box_id', $id)
                    ->find();

            if ($box_info) {
                $box_info['room_name'] = db('house')->where(['house_id' => $box_info['room_id']])->value('house_name');
                $box_info['unit_name'] = db('house')->where(['house_id' => $box_info['unit_id']])->value('house_name');
                $box_info['quarters_name'] = db('house')->where(['house_id' => $box_info['quarters_id']])->value('house_name');
            } else {
                $this->error('没有找到盒子信息');
            }

            $order_info = db('order')
                    ->where('user_box_id', $box_info['user_box_id'])
                    ->where('type', 4)
                    ->where('status', 1)
                    ->find();
            $order_id = 0;
            if ($order_info) {
                $order_id = $order_info['order_id'];
            } else {
                $order['order_no'] = 'BH' . time() . mt_rand(1000, 9999);
                $order['type'] = 4;
                $order['user_box_id'] = $box_info['user_box_id'];
                $order['status'] = 1;
                $order_id = db('order')->insertGetId($order);
            }

            $this->assign('info', $box_info);
            $this->assign('id', $order_id);
        }
        return $this->view->fetch();
    }

}
